<h1 class="text-center"><?php echo __("Live") . " " . $country; ?></h1>

          <div id="webroot" data-url='<?php echo $this->webroot; ?>' ></div>
          <div id="var" data-lang='<?php echo Configure::read("Config.lang"); ?>' 
          				data-country='<?php echo $country; ?>'></div>


          <div class="row">
            <div class="col-md-12" id="center_container">
                <div id="tournament-template" class="tournament hidden">
                        <div class="header-tournament-live">
                            <div class="country col-md-12"></div>
                        </div>
                        <div class="body-tournament-live"></div>
                </div>
                <div id="match-template" class="match hidden" data-static-id="">
                        <div class="header-match-live row">
                            <div class="time col-md-2"></div>
                            <div class="localteam col-md-3 text-right" text-right><a style="font-weight: 600"  class="team-popover" title="" rel="popover" data-placement="left" ></a></div>
                            <div class="score col-md-1"></div>
                            <div class="visitorteam col-md-3 text-left"><a style="font-weight: 600"  class="team-popover" title="" rel="popover" data-placement="left" ></a></div>
                            <div class="date col-md-2"></div>
                            <div class="odds-stats col-md-1"><a class='odds' title="<?php echo __("Quote"); ?>" href='#'><i class="glyphicon glyphicon-sound-5-1"></i></a><a href='#' class='stats' title="<?php echo __("Statistiche"); ?>" href=""><i class="glyphicon glyphicon-stats"></i></a></div>
                        </div>
                        <div class="body-match-live" style="display:none;"></div>
                </div>
                <div id="event-template" class="event row hidden">
                	<div class="col-md-12"><h4><?php echo __("Eventi"); ?></h4></div>
                </div>
                <div id="event-row-template" class="event-row row hidden" data-minute="0">
                  <div class="tdMinute col-md-2" ></div>
                  <div class="tdlocalteam col-md-3"></div>
                  <div class="tdScore col-md-2"></div>
                  <div class="tdvisitorteam col-md-3"></div>
                  <div class="empty col-md-2"></div>
                </div>

				<div id="lineups-template" class="lineups row hidden">
					<div class="col-md-12"><h4><?php echo __("Formazioni"); ?></h4></div>
					<div class="localteam-lineups col-md-5">

					</div>
					<div class="visitorteam-lineups col-md-6">

					</div>
				</div>
                <div id="lineups-row-template" class="lineups-row row" >
                  <div class="lineups-number col-md-5" ></div>
                  <div class="lineups-player col-md-5"></div>
                </div>
                
				<button id="start-stop" data-action="stop" class="btn btn-mini pull-right" style="margin-right: 20px;">Start/Stop <span id='countdown' class="badge">0</span></button>
				
				<div id="controls">
					<input type="radio" name="period" value="T" checked="cheecked" /> <?php echo __("Tutte"); ?>
					<input type="radio" name="period" value="I" /> <?php echo __("Solo in corso"); ?>
				</div>                
                    
                <div id="tournaments" class="" data-country='<?php echo $country; ?>' ></div>

            </div>
          </div>


<script>

    var countdown = new Countdown($('#countdown'),59,refresh);
    var countdownTimer = $.timer(function() {countdown.execute();},1000,true);

    $(document).ready(function() {
        // var interval = 1000 * 20; // where X is your every X seconds
        refresh();
        $('#start-stop').click(function(){
            if ($('#start-stop').data('action')=='stop') {
                countdownTimer.pause();
                $('#start-stop').data('action','start');
            } else {
                countdownTimer.play();
                $('#start-stop').data('action','stop');
            }
        });

        $('input[name="period"]:radio').change(function() {
        	refresh();
        });

        $(document).on('click', ".localteam", function() {
           $(this).parent().next().slideToggle("fast");
        });
        $(document).on('click', ".visitorteam", function() {
           $(this).parent().next().slideToggle("fast");
        });

    });
    
    function refresh() {
          country = $('#tournaments').data('country');
          url = "<?php echo $this -> webroot; ?>Feed/getLive/"+country;
          $.ajax({ type: "GET", url: url
            , dataType: "xml"
            , success: function(xml) {
                //console.log('refresh');
                $('#tournaments').empty();
              $(xml).find('tournament').each(function() {
                writeTournament($(this));
              });
            }
            , error: function(request, error, tipo_errore) { setFlash(error+': '+ tipo_errore, 'error'); }
          });
    }
    
    function lastMatchs(formatted_date) {
        var t_date = new Date(formatted_date.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1'));
        var today=new Date();
        var ventiquattroOre = 1000*60*60*$("input[name='period']:checked").val();
        var yesterday=today.getTime() - ventiquattroOre;
        // console.log(yesterday + ' - ' + t_date.getTime());
        // console.log(yesterday <= t_date.getTime());
        return (yesterday <= t_date.getTime());
    }

	function matchStatus(status) {
		if ($("input[name='period']:checked").val() == 'T')
			return true;
		else {
			if (status!='Full-time')
				return true;
			else
				return false;
		}
	}
    
    function writeTournament(tournament) {
        tournamentElement = $('#tournament-template').clone();
        HeaderTournamentElement = tournamentElement.children('.header-tournament-live');
        HeaderTournamentElement.children('.country').html(tournament.attr('name'));
        HeaderTournamentElement.children('.date').html(tournament.find('matches').attr('formatted_date'));
        tournament.find('match').each(function() {
            if (matchStatus($(this).attr('status')))
                tournamentElement.children('.body-tournament-live').append(writeMatch($(this)));
        });
        tournamentElement.removeAttr('id');
        tournamentElement.removeClass('hidden');
        tournamentElement.appendTo($('#tournaments'));
    }
    
    function writeMatch(match) {
        matchElement = $('#match-template').clone();
        localteam = match.find('localteam');
        visitorteam = match.find('visitorteam');
        // console.log(match.attr('static_id'));
        matchElement.data('static-id', match.attr('static_id'));
        // console.log(matchElement.data('static-id'));
        matchElement.children('.header-match-live').children('.localteam').children('a').html(localteam.attr('name'));
        matchElement.children('.header-match-live').children('.score').html('[' + localteam.attr('goals') + ' - ' + visitorteam.attr('goals') + ']');
        matchElement.children('.header-match-live').children('.visitorteam').children('a').html(visitorteam.attr('name'));
        matchElement.children('.header-match-live').children('.time').html(match.attr('time') + ' (' + match.attr('status') + ')');
        matchElement.children('.header-match-live').children('.date').html(match.attr('formatted_date'));
        matchElement.children('.header-match-live').children('.odds-stats').children('a.odds').attr('href',$('#webroot').data('url')+$('#var').data('lang')+'/odds/'+$('#var').data('country')+'/'+match.attr('static_id'));
        matchElement.children('.header-match-live').children('.odds-stats').children('a.stats').attr('href',$('#webroot').data('url')+$('#var').data('lang')+'/stats/match/'+localteam.attr('id')+'/'+visitorteam.attr('id'));

		// scrittura della formazione
        lineupsElement = $('#lineups-template').clone();
        writeLineups(lineupsElement,match);
        matchElement.children('.body-match-live').append(lineupsElement);
        lineupsElement.removeAttr('id');
        lineupsElement.removeClass('hidden');
        
		// scrittura degli eventi
        eventElement = $('#event-template').clone();
        // match.find('match').each(function() {
            writeEvent(eventElement,match);
        // });
        matchElement.children('.body-match-live').append(eventElement);
		
        eventElement.removeAttr('id');
        eventElement.removeClass('hidden');

        matchElement.removeAttr('id');
        matchElement.removeClass('hidden');
        return matchElement;
    }

    function writeTeamEvent(eventElement, eventData, team, type) {
        // console.log(eventData.attr('name'));
        eventRowElement = $('#event-row-template').clone();
        eventRowElement.data('minute', eventData.attr('minute'));
        eventRowElement.children('.td'+team).html('<div class="'+type+" "+team+'"></div> ' + eventData.attr('name'));
        eventRowElement.children('.tdMinute').html("<i class='fa-clock-o'></i> "+eventData.attr('minute'));
        // eventRowElement.children('.tdScore').html(eventData.attr('result'));
        eventRowElement.removeAttr('id');
        eventRowElement.removeClass('hidden');
        eventElement.append(eventRowElement);
    }

    function writeSubstitutionEvent(eventElement, eventData, team, type) {
        eventRowElement = $('#event-row-template').clone();
        eventRowElement.data('minute', eventData.attr('minute'));
        eventRowElement.children('.td'+team).html('<div class="'+type+" "+team+'"></div> ' + eventData.attr('off') + ' - ' + eventData.attr('on'));
        eventRowElement.children('.tdMinute').html("<i class='fa-clock-o'></i> "+eventData.attr('minute'));
        // eventRowElement.children('.tdScore').html(eventData.attr('result'));
        eventRowElement.removeAttr('id');
        eventRowElement.removeClass('hidden');
        eventElement.append(eventRowElement);
        // return eventElement;
    }

    function writeEvent(eventElement, eventData) {
    	summary = eventData.find('summary');
        summary.find('localteam').find('goals').find('player').each(function() {
            writeTeamEvent(eventElement,$(this),'localteam','goal');
        });
        summary.find('visitorteam').find('goals').find('player').each(function() {
            writeTeamEvent(eventElement,$(this),'visitorteam','goal');
        });
        summary.find('localteam').find('yellowcards').find('player').each(function() {
            writeTeamEvent(eventElement,$(this),'localteam','yellowcard');
        });
        summary.find('visitorteam').find('yellowcards').find('player').each(function() {
            writeTeamEvent(eventElement,$(this),'visitorteam','yellowcard');
        });
        summary.find('localteam').find('redcards').find('player').each(function() {
            writeTeamEvent(eventElement,$(this),'localteam','redcard');
        });
        summary.find('visitorteam').find('redcards').find('player').each(function() {
            writeTeamEvent(eventElement,$(this),'visitorteam','redcard');
        });
    	substitutions = eventData.find('substitutions');
        substitutions.find('localteam').find('substitution').each(function() {
            writeSubstitutionEvent(eventElement,$(this),'localteam','substitution');
        });
        substitutions.find('visitorteam').find('substitution').each(function() {
            writeSubstitutionEvent(eventElement,$(this),'visitorteam','substitution');
        });
        sortEvent(eventElement);
    }

	function sortEvent(eventElement){
		l = eventElement.children('.event-row').length;
		for (i=0; i<l; i++ ) {
			sortEventRow(eventElement.children('.event-row').first());
		}
	}
	
	function sortEventRow(eventRow) {
		if(!eventRow.hasClass('event-row'))
			return;
		// console.log(eventRow.data('minute') + ' > ' + eventRow.next().data('minute'));
		if (eventRow.data('minute')!=undefined && eventRow.next().data('minute')!=undefined && $.isNumeric(eventRow.data('minute')) && $.isNumeric(eventRow.next().data('minute'))) {
			if (parseInt(eventRow.data('minute'))>parseInt(eventRow.next().data('minute'))) {
				eventRow.insertAfter(eventRow.next());
				sortEventRow(eventRow);
			} else
				sortEventRow(eventRow.next());
		} else
			sortEventRow(eventRow.next());
	}
	
    function writeLineups(lineupsElement, lineupsData) {
        teams = lineupsData.find('teams');
        
        teams.find('localteam').find('player').each(function () {
	    	// console.log($(this).attr('number'));
	        lineupsRowElement = $('#lineups-row-template').clone();
        	lineupsRowElement.children('.lineups-number').html($(this).attr('number'));
        	lineupsRowElement.children('.lineups-player').html($(this).attr('name'));
	        lineupsRowElement.removeAttr('id');
	        lineupsElement.children('.localteam-lineups').append(lineupsRowElement);
        });

        teams.find('visitorteam').find('player').each(function () {
	        lineupsRowElement = $('#lineups-row-template').clone();
        	lineupsRowElement.children('.lineups-number').html($(this).attr('number'));
        	lineupsRowElement.children('.lineups-player').html($(this).attr('name'));
	        lineupsRowElement.removeAttr('id');
	        lineupsElement.children('.visitorteam-lineups').append(lineupsRowElement);
        });
    }

</script>



